<!--
 * @Author: YMJ
 * @Date: 2020-10-30 10:48:20
-->
<template>
  <div>
    <tab-list
      ref="list"
      :searchs="searchs"
      :list-hedar="listHedar"
      :params="params"
      :api-function="apiFunction"
      other-show
      @init-params="initParams"
      @add-list="openEditBox()"
    >
      <span
        slot="levelStatus"
        slot-scope="scope"
        :style="`color:${
          scope.value.levelStatus === '2' ? '#F56C6C' :
          scope.value.levelStatus === '1' ? '#67C23A' : '#909399'
        }`"
      >
        {{
          scope.value.levelStatus === '2' ? '已停用' :
          scope.value.levelStatus === '1' ? '已启用' : '未启用'
        }}
      </span>
      <template slot="operate" slot-scope="scope">
        <el-button type="text" size="small" @click="openEditBox(scope.value.levelId)">编辑</el-button>
        <el-button type="text" size="small" @click="enableItem(scope.value)">{{ scope.value.levelStatus === '1' ? '停用' : '启用' }}</el-button>
        <el-button type="text" size="small" @click="deleteItem(scope.value.levelId)">删除</el-button>
      </template>
    </tab-list>
    <el-dialog
      :title="`${detail ? '编辑' : '添加'}会员等级`"
      :visible.sync="toastShow"
      :close-on-click-modal="false"
      width="40%"
      @open="$refs.form && $refs.form.resetForm()"
    >
      <edit-form
        ref="form"
        :rules="rules"
        :edit-list="editList"
        :form="form"
        @on-submit="addOrEdit()"
      >
        <el-input
          slot="slot1"
          v-model="form.slot1"
          slot-scope="scope"
          :disabled="form[scope.edit.relation] != '-1'"
          placeholder="好友上限"
        />
        <el-input
          slot="slot2"
          v-model="form.slot2"
          slot-scope="scope"
          :disabled="form[scope.edit.relation] != '-1'"
          placeholder="每日添加好友"
        />
      </edit-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="toastShow = false">取 消</el-button>
        <el-button type="primary" @click="$refs.form.ruleFrom()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 组件
import tabList from '@/components/admin/tab-list.vue'
import editForm from '@/components/admin/edit-form.vue'
// 公共方法
import { asyncApiFun, openMessageBox, initEditList, isNumber } from '@/utils/utils'
// 接口
import { levelAll, levelDetail, levelEnable, levelDelete, levelEdit, benefitsList } from '@/api/member.js'
// 页面配置
import { listHedar, searchs, rules, editList } from './config/grade.config'
export default {
  components: {
    tabList,
    editForm
  },
  data() {
    return {
      rules,
      editList: [],
      form: {},
      detail: null,
      toastShow: false,
      listHedar,
      searchs,
      params: {},
      apiFunction: levelAll,
      benefitsList: []
    }
  },
  methods: {
    // 启用
    enableItem(item) {
      const _content = (item.levelStatus === '1' ? '停用后，会员等级不作为套餐可选项，是否确认？' : '启用后，会员等级可作为套餐可选项，是否确认？')
      const _title = `${item.levelStatus === '1' ? '停用' : '启用'}会员等级`
      openMessageBox({
        content: _content,
        title: _title
      }, async boole => {
        if (boole) {
          const parasm = {
            id: item.levelId,
            status: (item.levelStatus === '1' ? '2' : '1')
          }
          const [res] = await asyncApiFun(levelEnable, parasm)
          if (res) this.$refs.list.getList()
        }
      })
    },
    // 删除
    deleteItem(id) {
      openMessageBox({
        content: '删除数据后，将不可恢复，是否确认？',
        title: '删除数据'
      }, async boole => {
        if (boole) {
          const [res] = await asyncApiFun(levelDelete, id)
          if (res) this.$refs.list.getList()
        }
      })
    },
    // 打开新增或修改弹窗
    openEditBox(id) {
      this.getDetail(id)
      this.toastShow = true
    },
    // 新增或编辑
    async addOrEdit() {
      const params = {
        levelName: this.form.levelName,
        benefits: []
      }

      let _msg = ''
      this.benefitsList.forEach(item => {
        item.benefitsVal = this.form[item.benefitsId]
        if (item.benefitsName === '好友上限' && item.benefitsVal === '-1') {
          if (!isNumber(this.form.slot1)) {
            _msg = '请输入正确的好友上限人数'
            return
          }
          item.benefitsVal = this.form.slot1
        }
        if (item.benefitsName === '每日添加好友' && item.benefitsVal === '-1') {
          if (!isNumber(this.form.slot2)) {
            _msg = '请输入正确的每日添加好友人数'
            return
          }
          item.benefitsVal = this.form.slot2
        }
        params.benefits.push(item)
      })
      if (_msg) return this.$message.error(_msg)

      const _method = this.detail ? 'put' : 'post'
      if (_method === 'put') params.levelId = this.detail.levelId
      const [res] = await asyncApiFun(levelEdit, params, _method)
      if (res) {
        this.$message.success(`${_method === 'put' ? '编辑' : '添加'}成功`)
        this.$refs.list.getList()
        this.toastShow = false
      }
    },
    // 列表项详情
    async getDetail(id) {
      let _detail = null
      if (id) {
        const [res] = await asyncApiFun(levelDetail, id)
        if (res) _detail = res.data
      } else {
        _detail = null
      }
      this.detail = _detail
      // 重置编辑框数据
      this.form = initEditList(editList, this.detail)
      let _dataArr
      if (this.detail) {
        _dataArr = _detail.benefits
      } else {
        const [res] = await asyncApiFun(benefitsList)
        _dataArr = res.data
      }

      this.getbenefitsList(_dataArr, Boolean(_detail))
    },
    // 初始化列表请求参数
    initParams(param) {
      this.params = param
    },
    // 获取会员权益
    async getbenefitsList(dataArr, statu) {
      const _arr = []
      const _form = { levelName: (this.detail && this.detail.levelName) || '' }
      dataArr.forEach(item => {
        this.rules[item.benefitsId] = { required: true, message: `请选择${item.benefitsName}` }

        if (statu) {
          if (item.benefitsName === '好友上限' && item.benefitsVal !== '-2') {
            _form.slot1 = item.benefitsVal
            item.benefitsVal = '-1'
          }
          if (item.benefitsName === '每日添加好友' && item.benefitsVal !== '-2') {
            _form.slot2 = item.benefitsVal
            item.benefitsVal = '-1'
          }
        }
        _form[item.benefitsId] = item.benefitsVal

        // 构造会员权益
        const _obj = {
          type: 'radio',
          key: item.benefitsId,
          label: `${item.benefitsName}: `,
          data: [
            { title: this.getBenefitsName(item)[0], value: '-1' },
            { title: this.getBenefitsName(item)[1], value: '-2' }
          ]
        }
        _arr.push(_obj)
      })
      const _editList = JSON.parse(JSON.stringify(editList))
      _editList.splice(1, 0, ..._arr)
      this.benefitsList = dataArr
      this.editList = _editList
      this.form = _form
      this.$refs.form && this.$refs.form.resetForm()
    },
    // 获取label名字
    getBenefitsName(item) {
      let _arr = []
      switch (item.benefitsName) {
        case '会员标识':
          _arr = ['显示', '隐藏']
          break
        case '个性化名片':
          _arr = ['标准模板', '自定义名片']
          break
        case '畅览人脉':
        case '查看访客':
          _arr = ['可查看', '不可查看']
          break
        case '极速联系':
          _arr = ['无需交换名片', '需交换名片']
          break
        case '好友上限':
          _arr = ['是', '否']
          editList[1].relation = item.benefitsId
          break
        case '每日添加好友':
          editList[2].relation = item.benefitsId
          _arr = ['是', '否']
          break
        default:
          _arr = ['是', '否']
          break
      }
      return _arr
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog{
    max-height: 80%;
    overflow: auto;
  }
</style>
